<template>
      
    <h1>词条管理页面</h1>
<el-tabs v-model="activeName" @tab-click="handleClick">
  <el-tab-pane label="审核管理" name="review">
    <el-table :data="reviewData" style="width: 100%" height="500px">
      <el-table-column fixed prop="bid" label="业务编号" width="150" />
      <el-table-column prop="upload_datetime" label="上传时间" width="150" />
      <el-table-column prop="contributor" label="上传者" width="120" />
      <el-table-column prop="keywords" label="关键词" width="120" />
      <el-table-column prop="original" label="原文文案" width="320" />
      <el-table-column prop="target" label="目标语言文案" width="320" />
      <el-table-column prop="keep_period" label="等待审批时长" width="120" /> 
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="approve(scope.row)"
            >批准</el-button
          >
          <el-button link type="primary" @click="playaudio(scope.row.pronunciation)" size="small">播放语音</el-button>
        </template>
      </el-table-column>
    </el-table>

      <div v-if="total_page_size" >
          <el-pagination 
          @current-change="pageChange" 
          layout="prev, pager, next"
          :page-size=page_size
          :page-count=total_page_size
          :page-sizes="[1,10,30,50]"
          >
          </el-pagination>
        </div>
  </el-tab-pane>

  <el-tab-pane label="推荐管理" name="promotion">
    <el-button type="primary" @click="goto_promotionPage">查看推荐页面</el-button>
    <el-table :data="promotionData" style="width: 100%" height="500px">
      <el-table-column fixed prop="bid" label="业务编号" width="150" />
      <el-table-column prop="upload_datetime" label="上传时间" width="150" />
      <el-table-column prop="creator" label="上传者" width="120" />
      <el-table-column prop="key_words" label="关键词" width="120" />
      <el-table-column prop="origin_text" label="原文文案" width="320" />
      <el-table-column prop="target_text" label="目标语言文案" width="320" />
      <el-table-column prop="is_promotion" label="是否推荐" width="120" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button link type="primary" v-if='scope.row.is_promotion!="已推荐"' size="small" @click="promot(scope.row,1)"
            >推荐</el-button>
          <el-button link type="primary" v-else size="small" @click="promot(scope.row,0)"
            >取消推荐 </el-button>
          <el-button link type="primary" @click="playaudio(scope.row.pronunciation)" size="small">播放语音</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="promotion_total_page_size" >
      <el-pagination 
      @current-change="promotion_pageChange" 
      layout="prev, pager, next"
      :page-size=promotion_page_size
      :page-count=promotion_total_page_size
      :page-sizes="[1,10,30,50]"
      >
      </el-pagination>
    </div>
  </el-tab-pane>
</el-tabs>

<audio ref="audio" @ended="audioEnded"></audio>

  </template>
  
  <script>
  
  import axios from 'axios'
  import config from '../../spoken.config.json'
  import { ElNotification } from 'element-plus'
  import {JSEncrypt} from 'jsencrypt'
  import { onMounted, reactive, watch } from 'vue'
  
  export default {
    name: 'ReviewPage',
    props: {
      msg: String
    },
   
    
    data(){
        return{
            nick_name:null,
            user_id:null,
            avatar:null,
            page:1,
            page_size:config.PAGE_SIZE,
            total_page_size:null,
            promotion_page:1,
            promotion_page_size:config.PAGE_SIZE,
            promotion_total_page_size:null,
            reviewData:[],
            promotionData:[],
            is_promotion:false,
            activeName:'review',
        }
  },

  created(){
    this.user_profiles();
    this.get_assets_reviewData()
   },

 
  methods:{
    //页面初始化
      async user_profiles(){
        //读cookie，获取用户token
        const login_token= this.$commonFunctions.get_cookies('login_token')
        console.log("Console页面初始化数据。login_token："+login_token);
        
        const user_profiles= await this.$commonFunctions.get_user_profiles(login_token);
        
        this.nick_name=user_profiles.name
        this.avatar=user_profiles.avatar
        this.user_id=user_profiles.user_id

        //把昵称和头像信息存到cookie里
        
        console.log("后台管理-词条管理页面初始化数据。用户名："+this.nick_name+" 头像地址："+this.avatar+" 管理员标识："+user_profiles.is_superuser);
        },
          
    
        async get_assets_promotionData(){
          const data={
                        "type":1, // 1 = 词条  
                        "page":this.promotion_page, //当前页
                        "page_size":config.PAGE_SIZE,
                    }
          console.log("查询可使用词条入参检查"+JSON.stringify(data))
          await axios.post("/api/check_manageable_data_assets/", data, { withCredentials: true })
                .then(response => {
                  try {
                    console.log("check_promotionData的出参检查"+response.data["code"])
                    if (response.data["code"]==20000) {
                        console.log("this.promotionData:"+response.data["data"])
                        this.promotionData=response.data["data"]
                      
                        this.promotionData.forEach(element => {
                          if(element.is_promotion ==true){
                            element.is_promotion='已推荐'
                            element
                          }else{
                            element.is_promotion='未推荐'
                          }

                        });

                        this.$nextTick(()=>{
                        console.log("当前表格的总页数："+response.data["max_size"])
                        this.promotion_total_page_size=Number(response.data["max_size"]);
                      })
                     
                      }
                                            
                      if(this.promotionData.length==config.PAGE_SIZE){
                          this.promotion_page++;
                          // this.stopQuery=false;
                      }else{
                              this.promotion_page=1;
                              // this.stopQuery=true;
                          }
                    }
                  catch(error){console.log(error)}
                 
              })
        },

        async get_assets_reviewData(){
        const data={
                        "type":1,     //1=词条，2=课程
                        "page":this.page, //当前页
                        "page_size":config.PAGE_SIZE,
                    }
        console.log("查询待审核数据入参检查"+JSON.stringify(data));
        await axios.post("/api/check_reviewData/", data, { withCredentials: true })
                .then(response => {
                try {
                    console.log("check_reviewData的出参检查"+response.data["code"])
                    if (response.data["code"]==20000) {
                      this.reviewData=[]
                      console.log("查询开始前this.reviewData:"+this.reviewData)
                      
                      this.$nextTick(()=>{
                      console.log("当前表格的总页数："+response.data["max_size"])
                      this.total_page_size=Number(response.data["max_size"]);

                    
                      response.data["set"].forEach(element => {
                        console.log(element)
                        const startTime = new Date(element.upload_datetime).getTime(); 
                        const seconds = Math.floor(new Date().getTime()/1000 - startTime / 1000);
                        console.log(seconds)  
                        const minutes = Math.floor(seconds / 60); 
                        console.log(minutes)   
                        const hours = Math.floor(minutes / 60);  
                        console.log(hours)  
                        const days = Math.floor(hours / 24); 
                        console.log(days)   
                        const elapsed=`已等待 ${days} 天 ${hours % 24} 小时 ${minutes % 60} 分 ${seconds % 60} 秒`
                        console.log(elapsed)
                        let data={
                          "bid":element.business_id,
                          "upload_datetime":element.upload_datetime,
                          "contributor":element.contributor,
                          "keywords":element.keywords,
                          "original":element.original,
                          "target":element.target,
                          "pronunciation":element.pronunciation,
                          "keep_period":elapsed
                        }
                        console.log("检查data："+JSON.stringify(data))
                        this.reviewData.push(data)
                        console.log(this.reviewData)
                      });
                      
                      console.log("查询结束后this.reviewData:"+JSON.stringify(this.reviewData))
                      
                      if(this.reviewData.length==config.PAGE_SIZE){
                          this.page++;
                          // this.stopQuery=false;
                      }else{
                              this.page=1;
                              // this.stopQuery=true;
                          }
                    })
                  }else{
                          ElNotification({
                              message: response.msg,
                              title: "待审核数据",
                              type: "info",
                              duration: 3000,
                          }); 
                        }
                }
                catch(error){console.log(error)}
              })
      },

      pageChange(val){
                console.log(val)
                this.page=val
                this.get_assets_reviewData()
            },

      promotion_pageChange(val){
                console.log(val)
                this.promotion_page=val
                this.get_assets_promotionData()
            },

      async approve(row){
        console.log("approve函数入参检查"+JSON.stringify(row))
        //调用审核接口
        const data={
          "type":1,  // 1=词条
          "bid":row.bid,
          "value":2 // 0=冻结 1=待审核 2=通过审核
        }
        const res=await axios.post("/api/do_approval/",data,{withCredentials:true})
        console.log("approve函数出参检查"+JSON.stringify(res)) 
        //返回审核结果
        if (res.data["code"]==20000){
          ElNotification({
                title: '审核操作',
                message: '审核通过',
                type: 'success',
          })
        }else{
          ElNotification({
                title: '审核操作',
                message: '操作失败，请重试',
                type: 'error',
          })
        }

        //刷新数据表格
        this.get_assets_reviewData()
      },

      playaudio(url){
        console.log(JSON.stringify(url))
        if( url!=null || url!=undefined){
          try{
                this.$refs.audio.load();
                console.log("朗读地址："+url)
                this.$refs.audio.src=url;
                this.$refs.audio.play();
              
            }catch(error){
              console.log(error);
            }
        }
      },
    
    //播放完成清空audio src
    audioEnded(){
      console.log("audioEnded !");
      this.$refs.audio.src='';
      this.$refs.audio.load();
    },

    handleClick(tab){
      const dataSource=tab.props.name
      if(dataSource=='review'){
        this.get_assets_reviewData()
      }else if(dataSource=='promotion'){
        this.get_assets_promotionData()
      }
    },

    goto_promotionPage(){
      this.$router.push({ path: '/H5promotion/',query:{source:'recommand'} })
    },

    async promot(item,method){
      
        const data={
          "method":method, //1=推荐 0= 取消推荐
          "bid":item.bid
        }
        // 推荐
        await axios.post("/api/check_op_promotion/", data, { withCredentials: true })
                .then(response => {
                  try {
                    console.log(response)
                    if(response.data["code"]==20000){
                      ElNotification({
                        message: response.data["msg"],
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    });  
                    }else{
                      ElNotification({
                        message: response.data["msg"],
                        title: "系统消息",
                        type: "warning",
                        duration: 3000,
                    }); 
                    }
                    this.get_assets_promotionData()
             }catch(error){console.log(error)} 
          })
      },
  },
 
}
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped>
  
  </style>
  